#!/usr/bin/python

import sys
import matplotlib.pyplot as plt
import pylab
import random

file1name = sys.argv[1]
f1 = open(file1name, "rU")
fl1 = f1.readlines()

file2name = sys.argv[2]
f2 = open(file2name, "rU")
fl2 = f2.readlines()

line = fl2[4]
l = line.split('\t')
genomesize = int(l[7])

x1 = []
x2 = []
y1 = []
y2 = []

for i, line in enumerate(fl1):
    l = line.split('\t')
    start = int(l[0])
    stop = int(l[1].rstrip())
    x1.append(start)
    x2.append(stop)
    increment = 2 + (i * 0.01)
    y1.append(increment)
    y2.append(increment)

binned_counts = {}
for i in range(1, genomesize+1):
    binned_counts[i] = 0

for i, line in enumerate(fl2[4:]):
    l = line.split('\t')
    start = int(l[0])
    stop = int(l[1])
    iden = float(l[6])
    for a in range(start, stop):
        binned_counts[a] = binned_counts[a] + 1

cov = []

for k, v in binned_counts.iteritems():
    cov.append(v)
xcoords = range(1, genomesize+1)

gx = [1,genomesize]
gy = [1,1]

y1.sort()
y2.sort()

a = [x1, x2]
b = [y1, y2]

################################################################################
print "Plotting..."

fig = plt.figure(1, figsize=(14,8))

plt.subplot(211)
plt.plot(gx, gy, color='blue', marker='|', markersize=8.0,
    mec='black', ls='-', lw=2.0)
plt.plot(a, b, color='purple', linestyle='-')
plt.axis([1, 4721396, 0, 620])
plt.title('Paired-end clones')
plt.ylabel('Tiled clone pairs')

frame1 = plt.gca()
for tick in frame1.axes.get_yticklines():
    tick.set_visible(False)
for y in frame1.axes.get_yticklabels():
    y.set_visible(False)
plt.grid(True)


plt.subplot(212)
plt.fill_between(xcoords, cov, facecolor='#33FF33', alpha=0.4)
plt.xlabel('Genome position (bp)')
plt.ylabel('Counts of binned reads (per 1000bp)')
plt.axis([1, genomesize, 0, max(cov)+2])
plt.grid(True)

plt.show()

